﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;

namespace Project
{
    public class SoundManager
    {
        private Dictionary<string, SoundEffectInstance> sounds = new Dictionary<string, SoundEffectInstance>();
        private ContentManager content;

        public Vector3 listenerPosition;

        public SoundManager(ContentManager content)
        {
            this.content = content;
        }

        public void playSoundOnce(string s)
        {
            SoundEffect soundEngine = content.Load<SoundEffect>(s);
            SoundEffectInstance soundEngineInstanceOne = soundEngine.CreateInstance();
            soundEngineInstanceOne.Play();
        }
        private void loadAndPlaySound(string filename, float volume, bool loop) {
            SoundEffect soundEngine = content.Load<SoundEffect>(filename);
            SoundEffectInstance soundEngineInstance = soundEngine.CreateInstance();
            sounds.Add(filename, soundEngineInstance);

            soundEngineInstance.IsLooped = false;
            soundEngineInstance.Volume = volume;
            soundEngineInstance.Play();
        }
        public void playSound(string filename, float volume, bool loop)
        {
            if (sounds.ContainsKey(filename))
            {
                SoundEffectInstance soundEngineInstance = sounds[filename];
                if (soundEngineInstance.State == SoundState.Paused)
                {
                    soundEngineInstance.Resume();
                }
                else if (soundEngineInstance.State == SoundState.Stopped)
                {
                    soundEngineInstance.Play();
                }
            }
            else
            {
                loadAndPlaySound(filename, volume, loop);
            }
        }

        public void playSound(string filename, Vector3 location, bool loop)
        {
            float dist = (location - this.listenerPosition).Length();
            playSound(filename, 1 / (dist * dist), loop);
        }

        public void pauseSound(string s)
        {

            SoundEffectInstance soundEngineInstance;
            if (sounds.ContainsKey(s))
            {
                soundEngineInstance = sounds[s];
                if (soundEngineInstance.State == SoundState.Playing)
                {
                    soundEngineInstance.Pause();
                }
                sounds[s] = soundEngineInstance;
            }
        }
    }
}